//
//  MailComposerDelegate.m
//  EmailExtensionIOS
//
//  Based on the example by Piotr Kościerzyński, http://flashsimulations.com/2011/11/30/ios-native-extension-for-adobe-air-in-app-mail-composer/

#import "MailComposerDelegate.h"
#import "MailComposeViewControllerWrapper.h"

// Note: Uncomment the line below, if you use the extension with Adobe AIR 3.2 or lower.
// This category provides a workaround for a bug in these SDKs, which affects orientation.
//#import "UIViewController+Orientation.h"


@implementation MailComposerDelegate
static NSString *attachmentsSeparator = @"----";
static NSString *event_name = @"MAIL_COMPOSER_EVENT";

- (id)init
{
    self = [super init];
    
    if (self) 
    {
    }
    
    return self;
}

- (void)dealloc
{
    context = NULL;
    [ super dealloc ];
}


-( void ) sendEmail : ( NSString * ) subject 
       toRecipients : ( NSString * ) toRecipients 
       ccRecipients : ( NSString * ) ccRecipients 
      bccRecipients : ( NSString * ) bccRecipients 
        messageBody : ( NSString * ) messageBody 
            useHtml : ( Boolean )    useHtml
    attachmentsData : ( NSString * ) attachmentsData
{
    assert( NULL != context );
    
    MailComposeViewControllerWrapper * mailComposer = [ [ MailComposeViewControllerWrapper alloc ] init ];
	mailComposer.mailComposeDelegate = self;
    
    if ( NULL != subject)
    {
        [ mailComposer setSubject : subject ]; 
    }
    
    if ( NULL != messageBody )
    {
        [ mailComposer setMessageBody : messageBody isHTML : useHtml ];
    }
    
    if ( NULL != toRecipients && [ toRecipients rangeOfString : @"@" ].location != NSNotFound ) 
    {
        [ mailComposer setToRecipients : [ toRecipients componentsSeparatedByString : @"," ] ];
    }
    
    if ( NULL != ccRecipients && [ ccRecipients rangeOfString : @"@" ].location != NSNotFound ) 
    {
        [ mailComposer setCcRecipients : [ ccRecipients componentsSeparatedByString : @"," ] ];
    }
    
    if ( NULL != bccRecipients && [ bccRecipients rangeOfString : @"@" ].location != NSNotFound ) 
    {
        [ mailComposer setBccRecipients : [ bccRecipients componentsSeparatedByString : @"," ] ];
    }
    
    
    if ( NULL != attachmentsData ) 
    {      
        NSArray *attachments = [attachmentsData componentsSeparatedByString:attachmentsSeparator];
        
        static NSString *attachmentPropertySeparator = @"|";
        
        for ( NSString * attachmentEntry in attachments ) 
        {
            NSArray  * attachmentProperties = [ attachmentEntry componentsSeparatedByString : attachmentPropertySeparator ];
            
            NSString * filePath = [ attachmentProperties objectAtIndex : 0 ];
            NSString * fileMimeType = [ attachmentProperties objectAtIndex : 1 ];
            NSString * fileAttachName = [ attachmentProperties objectAtIndex : 2 ];
            
            if ( [ [ NSFileManager defaultManager ] fileExistsAtPath : filePath ] ) 
            {
                NSData * fileData = [ [ NSData alloc ] initWithContentsOfFile : filePath ];
                
                if ( fileData ) 
                {
                    [ mailComposer addAttachmentData : fileData mimeType : fileMimeType fileName : fileAttachName ];            
                }
                
                [ fileData release ];
            }
        }
    }
    
// Older version: see below for the newer call
//    [[[[UIApplication sharedApplication] keyWindow] rootViewController] presentModalViewController:mailComposer animated:YES];
    
//  This is the newer version, which however requires iOS 5.0 or later
  [[[[UIApplication sharedApplication] keyWindow] rootViewController] presentViewController:mailComposer animated:YES completion:NULL];
    
	[ mailComposer release ];
}


-( void ) notifyMailComposerDismissed 
{
    FREDispatchStatusEventAsync(context, (uint8_t*)[event_name UTF8String], (uint8_t*)[@"MAIL_COMPOSER_DISMISSED" UTF8String]);
}


-(void) mailComposeController: (MFMailComposeViewController*)controller didFinishWithResult: (MFMailComposeResult)result error:(NSError*)error
{	
    NSString *event_info = @"";

	switch (result)
	{
		case MFMailComposeResultCancelled:
            event_info = @"MAIL_CANCELLED";
			break;
		case MFMailComposeResultSaved:
            event_info = @"MAIL_SAVED";
			break;
		case MFMailComposeResultSent:
            event_info = @"MAIL_SENT";
			break;
		case MFMailComposeResultFailed:
            event_info = @"MAIL_FAILED";
			break;
		default:
            event_info = @"MAIL_UNKNOWN";
            break;
	}
    
    FREDispatchStatusEventAsync( context, ( uint8_t * )[ event_name UTF8String ], ( uint8_t * )[ event_info UTF8String ] );

// Older version: see below for the newer call
//    [[[[UIApplication sharedApplication] keyWindow] rootViewController] dismissModalViewControllerAnimated:YES];
//    FREDispatchStatusEventAsync( *context, ( uint8_t * )[ event_name UTF8String ], ( uint8_t * )[ @"MAIL_COMPOSER_DISMISSED" UTF8String ] );
    
//  This is the newer version, which however requires iOS 5.0 or later.
//  It gives you the chance of timing the firing of the MAIL_COMPOSER_DISMISSED event better, as it will fire when the composer has finished being dismissed:
    [[[[UIApplication sharedApplication] keyWindow] rootViewController] dismissViewControllerAnimated:YES completion: ^(void){ [ self notifyMailComposerDismissed ]; }];
}


-( void ) setContext:( FREContext ) ctx
{
    context = ctx;
}

@end
